import numpy as np
import pandas as pd
import seaborn as sns; sns.set(style="ticks", color_codes=True)
import matplotlib.pyplot as plt
import plotly.graph_objs as go
from plotly.subplots import make_subplots
import seaborn as sns
import plotly.express as px
%matplotlib inline
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected = False)
Cargar el conjunto de datos en el entorno de trabajo
Realizar una revisión general
dataset original
#Importación de dataset desde github
url = 'https://github.com/No-Country-simulation/c22-34-n-data-bi/blob/main/DATA/afluencia_diaria_pasajeros_10_2024_limpios.csv'
#url='https://github.com/ISPC-PP1-2024/proyecto/blob/main/datos/DataCoSupplyChainDataset/SinAcento.csv' //usar este para el desarrollo, corrige acentos
df_1 = pd.read_csv(url)
--------------------------------------------------------------------------- HTTPError Traceback (most recent call last) Cell In[620], line 5 2 url = 'https://github.com/No-Country-simulation/c22-34-n-data-bi/blob/main/DATA/afluencia_diaria_pasajeros_10_2024_limpios.csv' 4 #url='https://github.com/ISPC-PP1-2024/proyecto/blob/main/datos/DataCoSupplyChainDataset/SinAcento.csv' //usar este para el desarrollo, corrige acentos ----> 5 df_1 = pd.read_csv(url) File ~\anaconda3\lib\site-packages\pandas\io\parsers\readers.py:1026, in read_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, date_format, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, encoding_errors, dialect, on_bad_lines, delim_whitespace, low_memory, memory_map, float_precision, storage_options, dtype_backend) 1013 kwds_defaults = _refine_defaults_read( 1014 dialect, 1015 delimiter, (...) 1022 dtype_backend=dtype_backend, 1023 ) 1024 kwds.update(kwds_defaults) -> 1026 return _read(filepath_or_buffer, kwds) File ~\anaconda3\lib\site-packages\pandas\io\parsers\readers.py:620, in _read(filepath_or_buffer, kwds) 617 _validate_names(kwds.get("names", None)) 619 # Create the parser. --> 620 parser = TextFileReader(filepath_or_buffer, **kwds) 622 if chunksize or iterator: 623 return parser File ~\anaconda3\lib\site-packages\pandas\io\parsers\readers.py:1620, in TextFileReader.__init__(self, f, engine, **kwds) 1617 self.options["has_index_names"] = kwds["has_index_names"] 1619 self.handles: IOHandles | None = None -> 1620 self._engine = self._make_engine(f, self.engine) File ~\anaconda3\lib\site-packages\pandas\io\parsers\readers.py:1880, in TextFileReader._make_engine(self, f, engine) 1878 if "b" not in mode: 1879 mode += "b" -> 1880 self.handles = get_handle( 1881 f, 1882 mode, 1883 encoding=self.options.get("encoding", None), 1884 compression=self.options.get("compression", None), 1885 memory_map=self.options.get("memory_map", False), 1886 is_text=is_text, 1887 errors=self.options.get("encoding_errors", "strict"), 1888 storage_options=self.options.get("storage_options", None), 1889 ) 1890 assert self.handles is not None 1891 f = self.handles.handle File ~\anaconda3\lib\site-packages\pandas\io\common.py:728, in get_handle(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options) 725 codecs.lookup_error(errors) 727 # open URLs --> 728 ioargs = _get_filepath_or_buffer( 729 path_or_buf, 730 encoding=encoding, 731 compression=compression, 732 mode=mode, 733 storage_options=storage_options, 734 ) 736 handle = ioargs.filepath_or_buffer 737 handles: list[BaseBuffer] File ~\anaconda3\lib\site-packages\pandas\io\common.py:384, in _get_filepath_or_buffer(filepath_or_buffer, encoding, compression, mode, storage_options) 382 # assuming storage_options is to be interpreted as headers 383 req_info = urllib.request.Request(filepath_or_buffer, headers=storage_options) --> 384 with urlopen(req_info) as req: 385 content_encoding = req.headers.get("Content-Encoding", None) 386 if content_encoding == "gzip": 387 # Override compression based on Content-Encoding header File ~\anaconda3\lib\site-packages\pandas\io\common.py:289, in urlopen(*args, **kwargs) 283 """ 284 Lazy-import wrapper for stdlib urlopen, as that imports a big chunk of 285 the stdlib. 286 """ 287 import urllib.request --> 289 return urllib.request.urlopen(*args, **kwargs) File ~\anaconda3\lib\urllib\request.py:216, in urlopen(url, data, timeout, cafile, capath, cadefault, context) 214 else: 215 opener = _opener --> 216 return opener.open(url, data, timeout) File ~\anaconda3\lib\urllib\request.py:525, in OpenerDirector.open(self, fullurl, data, timeout) 523 for processor in self.process_response.get(protocol, []): 524 meth = getattr(processor, meth_name) --> 525 response = meth(req, response) 527 return response File ~\anaconda3\lib\urllib\request.py:634, in HTTPErrorProcessor.http_response(self, request, response) 631 # According to RFC 2616, "2xx" code indicates that the client's 632 # request was successfully received, understood, and accepted. 633 if not (200 <= code < 300): --> 634 response = self.parent.error( 635 'http', request, response, code, msg, hdrs) 637 return response File ~\anaconda3\lib\urllib\request.py:563, in OpenerDirector.error(self, proto, *args) 561 if http_err: 562 args = (dict, 'default', 'http_error_default') + orig_args --> 563 return self._call_chain(*args) File ~\anaconda3\lib\urllib\request.py:496, in OpenerDirector._call_chain(self, chain, kind, meth_name, *args) 494 for handler in handlers: 495 func = getattr(handler, meth_name) --> 496 result = func(*args) 497 if result is not None: 498 return result File ~\anaconda3\lib\urllib\request.py:643, in HTTPDefaultErrorHandler.http_error_default(self, req, fp, code, msg, hdrs) 642 def http_error_default(self, req, fp, code, msg, hdrs): --> 643 raise HTTPError(req.full_url, code, msg, hdrs, fp) HTTPError: HTTP Error 404: Not Found
# dataset original -para jupyter
#df_1=pd.read_csv('C:\\Users\\Usuario\\Desktop\\2024\\materias\\CDIA\\2semestre\\pp1-cdia23\\ejemplo suply chain\\DataCoSupplyChainDataset.csv\\para jupyter\\SinAcento.csv', encoding='latin1', sep=';', low_memory=False)
#df_1=pd.read_csv('C:\\Users\\Usuario\\Desktop\\descargas de pdfs\\NOCOUNTRY\\grupo propio\\datasettodos_juntos_ok.csv', encoding='latin1', sep=';', low_memory=False)
df_1 = pd.read_csv(r'C:\Users\Usuario\Desktop\descargas de pdfs\NOCOUNTRY\grupo propio\dataset\angela\afluencia_diaria_pasajeros_10_2024_limpios.csv',
encoding='latin1', sep=';', low_memory=False)
#C:\\Users\\Usuario\\Desktop\\descargas de pdfs\\NOCOUNTRY\\grupo propio\\datasettodos_juntos_ok.csv
pd.set_option('display.max_rows', 60) #muestra 60 columnas
pd.set_option('display.max_columns', 100) # 100 filas
pd.set_option('display.width', 1000)
df_1.shape
(26266, 7)
# detalle
df_1.head()
| date | month | year | service | type_paiment | affluence | num_month | |
|---|---|---|---|---|---|---|---|
| 0 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Boleto | 0 | 1 |
| 1 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Prepago | 0 | 1 |
| 2 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Gratuidad | 0 | 1 |
| 3 | 1/1/2022 | Enero | 2022 | Atenea | Boleto | 2702 | 1 |
| 4 | 1/1/2022 | Enero | 2022 | Atenea | Prepago | 0 | 1 |
# tamaño en filas y columnas del dataset original
df_1.shape
(26266, 7)
df=df_1
#Mostrar los primeras filas del dataframe resultante
df.head()
| date | month | year | service | type_paiment | affluence | num_month | |
|---|---|---|---|---|---|---|---|
| 0 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Boleto | 0 | 1 |
| 1 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Prepago | 0 | 1 |
| 2 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Gratuidad | 0 | 1 |
| 3 | 1/1/2022 | Enero | 2022 | Atenea | Boleto | 2702 | 1 |
| 4 | 1/1/2022 | Enero | 2022 | Atenea | Prepago | 0 | 1 |
df.shape
(26266, 7)
#Mostrar las ultimas filas del dataframe resultante
df.tail()
| date | month | year | service | type_paiment | affluence | num_month | |
|---|---|---|---|---|---|---|---|
| 26261 | 31/10/2024 | Octubre | 2024 | ORDINARIO | Prepago | 60887 | 10 |
| 26262 | 31/10/2024 | Octubre | 2024 | ORDINARIO | Gratuidad | 12157 | 10 |
| 26263 | 31/10/2024 | Octubre | 2024 | S/METRO | Boleto | 3442 | 10 |
| 26264 | 31/10/2024 | Octubre | 2024 | S/METRO | Prepago | 31434 | 10 |
| 26265 | 31/10/2024 | Octubre | 2024 | S/METRO | Gratuidad | 6872 | 10 |
#Nuevo tamaño del dataframe
df.shape
(26266, 7)
Información general del DataFrame ---tipo de datos---
df.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 26266 entries, 0 to 26265 Data columns (total 7 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 date 26266 non-null object 1 month 26266 non-null object 2 year 26266 non-null int64 3 service 26266 non-null object 4 type_paiment 26266 non-null object 5 affluence 26266 non-null int64 6 num_month 26266 non-null int64 dtypes: int64(3), object(4) memory usage: 1.4+ MB
Verificar si existen filas duplicadas o espacios vacios.
# verificar filas duplicadas
duplicados=df[df.duplicated()]
if duplicados.empty:
print("No hay filas duplicadas en el DataFrame.")
else:
print("Las siguientes filas están duplicadas:")
print(duplicados)
No hay filas duplicadas en el DataFrame.
# verificar espacios vacios
hay_vacios = df.isna().any().any()
if hay_vacios:
print("El DataFrame contiene valores vacíos.")
else:
print("El DataFrame no contiene valores vacíos.")
El DataFrame no contiene valores vacíos.
De acuerdo a la informacion anterior, luego deberemos tratar las columnas precio y ventas
# Cantidad de valores nulos por columna
missing_data = df.isna().sum()
print(missing_data[missing_data > 0])
Series([], dtype: int64)
df.head(100)
| date | month | year | service | type_paiment | affluence | num_month | |
|---|---|---|---|---|---|---|---|
| 0 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Boleto | 0 | 1 |
| 1 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Prepago | 0 | 1 |
| 2 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Gratuidad | 0 | 1 |
| 3 | 1/1/2022 | Enero | 2022 | Atenea | Boleto | 2702 | 1 |
| 4 | 1/1/2022 | Enero | 2022 | Atenea | Prepago | 0 | 1 |
| ... | ... | ... | ... | ... | ... | ... | ... |
| 95 | 4/1/2022 | Enero | 2022 | Expdirecto | Gratuidad | 314 | 1 |
| 96 | 4/1/2022 | Enero | 2022 | Expreso | Boleto | 47758 | 1 |
| 97 | 4/1/2022 | Enero | 2022 | Expreso | Prepago | 5535 | 1 |
| 98 | 4/1/2022 | Enero | 2022 | Expreso | Gratuidad | 8309 | 1 |
| 99 | 4/1/2022 | Enero | 2022 | Nochebús | Boleto | 724 | 1 |
100 rows × 7 columns
# Cantidad de valores nulos por columna
missing_data = df.isna().sum()
print(missing_data[missing_data > 0])
Series([], dtype: int64)
df.head()
| date | month | year | service | type_paiment | affluence | num_month | |
|---|---|---|---|---|---|---|---|
| 0 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Boleto | 0 | 1 |
| 1 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Prepago | 0 | 1 |
| 2 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Gratuidad | 0 | 1 |
| 3 | 1/1/2022 | Enero | 2022 | Atenea | Boleto | 2702 | 1 |
| 4 | 1/1/2022 | Enero | 2022 | Atenea | Prepago | 0 | 1 |
valores_distintos = sorted(df['service'].unique())
print("Valores distintos (ordenados):")
print(valores_distintos)
Valores distintos (ordenados): ['ATENEA', 'Apoyo Concesionado', 'Apoyo Metro L1', 'Apoyo concesionado', 'Atenea', 'CIRCUITO HOSPITALES', 'Circuito Hospitales', 'Circuito Hospitales $8.00', 'ECOB?S', 'EXPDIRECTO', 'EXPRESO', 'Ecoatenea', 'Ecobús', 'Expdirecto', 'Expreso', 'Expreso Directo', 'NOCHEB?S', 'Nochebús', 'ORDINARIO', 'Ordinario', 'S/METRO', 'S/Metro', 'SERVICIOS TEMPORALES', 'Servicios Temporales']
nombres de columnas
df.columns
Index(['date', 'month', 'year', 'service', 'type_paiment', 'affluence', 'num_month'], dtype='object')
df.head()
| date | month | year | service | type_paiment | affluence | num_month | |
|---|---|---|---|---|---|---|---|
| 0 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Boleto | 0 | 1 |
| 1 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Prepago | 0 | 1 |
| 2 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Gratuidad | 0 | 1 |
| 3 | 1/1/2022 | Enero | 2022 | Atenea | Boleto | 2702 | 1 |
| 4 | 1/1/2022 | Enero | 2022 | Atenea | Prepago | 0 | 1 |
# Columnas traducidas
df.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 26266 entries, 0 to 26265 Data columns (total 7 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 date 26266 non-null object 1 month 26266 non-null object 2 year 26266 non-null int64 3 service 26266 non-null object 4 type_paiment 26266 non-null object 5 affluence 26266 non-null int64 6 num_month 26266 non-null int64 dtypes: int64(3), object(4) memory usage: 1.4+ MB
#tamaño del nuevo dataframe
df.shape
(26266, 7)
Conteo de valores únicos por columna:
df.nunique()
date 1035 month 12 year 3 service 24 type_paiment 3 affluence 12980 num_month 12 dtype: int64
Verificar si existen filas duplicadas o espacios vacios.
# verificar filas duplicadas
duplicados=df[df.duplicated()]
if duplicados.empty:
print("No hay filas duplicadas en el DataFrame.")
else:
print("Las siguientes filas están duplicadas:")
print(duplicados)
No hay filas duplicadas en el DataFrame.
# verificar espacios vacios
hay_vacios = df.isna().any().any()
if hay_vacios:
print("El DataFrame contiene valores vacíos.")
else:
print("El DataFrame no contiene valores vacíos.")
El DataFrame no contiene valores vacíos.
valores_distintos = sorted(df['month'].unique())
print("Valores distintos (ordenados):")
print(valores_distintos)
Valores distintos (ordenados): ['Abril', 'Agosto', 'Diciembre', 'Enero', 'Febrero', 'Julio', 'Junio', 'Marzo', 'Mayo', 'Noviembre', 'Octubre', 'Septiembre']
# Cantidad de valores nulos por columna
missing_data = df.isna().sum()
print(missing_data[missing_data > 0])
Series([], dtype: int64)
df.head()
| date | month | year | service | type_paiment | affluence | num_month | |
|---|---|---|---|---|---|---|---|
| 0 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Boleto | 0 | 1 |
| 1 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Prepago | 0 | 1 |
| 2 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Gratuidad | 0 | 1 |
| 3 | 1/1/2022 | Enero | 2022 | Atenea | Boleto | 2702 | 1 |
| 4 | 1/1/2022 | Enero | 2022 | Atenea | Prepago | 0 | 1 |
# Cantidad de valores nulos por columna
missing_data = df_resultado.isna().sum()
print(missing_data[missing_data > 0])
Series([], dtype: int64)
# no quedan valores na
# hasta aqui esta bien
# FIN DE LA PRIMERA PARTE: Exploración Inicial de Datos
# 2 PARTE: ANALISIS UNIVARIADO
Distribución de Variables: Realizar un análisis de las variables individuales para entender su distribución. Utilizar histogramas, boxplots y estadísticas descriptivas (media, mediana, desviación estándar, etc.) para las variables numéricas. Para las variables categóricas, calcular frecuencias y proporciones.
Identificación de Outliers: Detectar posibles outliers en las variables numéricas utilizando técnicas como el análisis de boxplots o el cálculo del z-score.
hay que renombrar las lineas-.----
Cell In[427], line 1 hay que renombrar las lineas-.---- ^ SyntaxError: invalid syntax
Valores de Pago
df.type_paiment.unique()
array(['Boleto', 'Prepago', 'Gratuidad'], dtype=object)
Valores de servicio
df.service.unique()
array(['Servicios Temporales', 'Atenea', 'Ecoatenea', 'Ecobús',
'Expdirecto', 'Expreso', 'Nochebús', 'Ordinario', 'S/Metro',
'Apoyo Metro L1', 'Circuito Hospitales', 'Expreso Directo',
'Circuito Hospitales $8.00', 'Apoyo Concesionado',
'Apoyo concesionado', 'ATENEA', 'ECOB?S', 'EXPRESO', 'NOCHEB?S',
'ORDINARIO', 'S/METRO', 'EXPDIRECTO', 'CIRCUITO HOSPITALES',
'SERVICIOS TEMPORALES'], dtype=object)
Valores de Segmento de Clientes
#EXPLORAMOS LOS DATOS:
#Obtenemos estadísticas descriptivas sobre las columnas numéricas del conjunto de datos:
df.describe()
| year | affluence | num_month | |
|---|---|---|---|
| count | 26266.00000 | 26266.000000 | 26266.000000 |
| mean | 2022.91430 | 13099.603899 | 6.244118 |
| std | 0.81079 | 23602.472653 | 3.338865 |
| min | 2022.00000 | 0.000000 | 1.000000 |
| 25% | 2022.00000 | 232.000000 | 3.000000 |
| 50% | 2023.00000 | 2154.500000 | 6.000000 |
| 75% | 2024.00000 | 15126.750000 | 9.000000 |
| max | 2024.00000 | 148014.000000 | 12.000000 |
# Para cada COLUMNA NUMERICA DE INTERES calcular la mediana, MEDIA Y DESVIACION ESTANDAR
# EJEMPLO PARA Benefit per order Y PRECIO DE PRODUCTO
#histogramas, boxplots -valores atipicos
#Numero de pedidos y tiempo de entrega real
dias_entrega_real=df.groupby(['service'])['affluence'].count().reset_index(name='numero de pasajeros').sort_values(by= 'numero de pasajeros', ascending= False)
fig=px.bar(dias_entrega_real, x='service', y='numero de pasajeros' , color='service',
)
fig.show()
#Cantidad de pedidos segun categoria
dias_entrega_real=df.groupby(['type_paiment'])['affluence'].count().reset_index(name='Numero de pasajeros').sort_values(by= 'Numero de pasajeros', ascending= False)
fig=px.bar(dias_entrega_real, x='type_paiment', y='Numero de pasajeros' , color='type_paiment'
)
fig.show()
#Cantidad de productos segun categoria
dias_entrega_real=df.groupby(['year'])['affluence'].count().reset_index(name='cantidad de pasajeros').sort_values(by= 'cantidad de pasajeros', ascending= False)
fig=px.bar(dias_entrega_real, x='year', y='cantidad de pasajeros' , color='year'
)
fig.show()
#Cantidad de productos segun categoria
dias_entrega_real=df.groupby(['month'])['affluence'].count().reset_index(name='cantidad de pasajeros').sort_values(by= 'cantidad de pasajeros', ascending= False)
fig=px.bar(dias_entrega_real, x='month', y='cantidad de pasajeros' , color='month' )
fig.show()
# Agrupar por año y mes, y sumar la afluencia
dias_entrega_real = df.groupby(['year', 'month'])['affluence'].sum().reset_index(name='afluencia_total')
# Ordenar por afluencia total de mayor a menor
dias_entrega_real = dias_entrega_real.sort_values(by='afluencia_total', ascending=False)
# Crear el gráfico de barras
fig = px.bar(dias_entrega_real, x='month', y='afluencia_total', color='year',
barmode='group') # Mostrar barras agrupadas por año
fig.show()
# Agrupar por año y mes, y sumar la afluencia
dias_entrega_real = df.groupby(['year', 'service'])['affluence'].sum().reset_index(name='afluencia_total')
# Ordenar por afluencia total de mayor a menor
dias_entrega_real = dias_entrega_real.sort_values(by='afluencia_total', ascending=False)
# Crear el gráfico de barras
fig = px.bar(dias_entrega_real, x='year', y='afluencia_total', color='service',
barmode='group') # Mostrar barras agrupadas por año
fig.show()
# Agrupar por año y mes, y sumar la afluencia
dias_entrega_real = df.groupby(['year', 'type_paiment'])['affluence'].sum().reset_index(name='afluencia_total')
# Ordenar por afluencia total de mayor a menor
dias_entrega_real = dias_entrega_real.sort_values(by='afluencia_total', ascending=False)
# Crear el gráfico de barras
fig = px.bar(dias_entrega_real, x='year', y='afluencia_total', color='type_paiment',
barmode='group') # Mostrar barras agrupadas por año
fig.show()
---hasta aqui ok----
#Graficar
dias_entrega_real=df.groupby(['service'])['affluence'].sum().reset_index(name='Total servicios').sort_values(by= 'Total servicios', ascending= False)
fig=px.bar(dias_entrega_real, x='service', y='Total servicios' , color='service'
)
fig.show()
#Cantidad de pedidos segun el segmento de clientes
data_Customer_Segment=df.groupby(['type_paiment'])['affluence'].count().reset_index(name='Numero de afluencias').sort_values(by= 'Numero de afluencias', ascending= False)
fig=px.pie(data_Customer_Segment, values='Numero de afluencias', names= 'type_paiment' , title= 'Numbero de afluencias segun tipo de pago',
width=600 , height=600 , color_discrete_sequence = px.colors.qualitative.D3)
fig.show()
#Segmento de Clientes para la region de America del sur
df_argentina = df[df['service'] == 'Servicios Temporales']
data_Customer_Segment=df_argentina.groupby(['type_paiment'])['affluence'].count().reset_index(name='Numero de afluencias').sort_values(by= 'Numero de afluencias', ascending= False)
px.pie(data_Customer_Segment, values='Numero de afluencias', names= 'type_paiment' , title= 'Numbero de afluencias segun servicios temporales',
width=600 , height=600 , color_discrete_sequence = ["red", "green", "blue", "goldenrod", "magenta"])
#Segmento de Clientes para la region de America del sur
df_argentina = df[df['service'] == 'Nochebús']
data_Customer_Segment=df_argentina.groupby(['type_paiment'])['affluence'].count().reset_index(name='Numero de afluencias').sort_values(by= 'Numero de afluencias', ascending= False)
px.pie(data_Customer_Segment, values='Numero de afluencias', names= 'type_paiment' , title= 'Numbero de afluencias segun servicios express',
width=600 , height=600 , color_discrete_sequence = px.colors.qualitative.G10)
df.head()
| date | month | year | service | type_paiment | affluence | num_month | |
|---|---|---|---|---|---|---|---|
| 0 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Boleto | 0 | 1 |
| 1 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Prepago | 0 | 1 |
| 2 | 1/1/2022 | Enero | 2022 | Servicios Temporales | Gratuidad | 0 | 1 |
| 3 | 1/1/2022 | Enero | 2022 | Atenea | Boleto | 2702 | 1 |
| 4 | 1/1/2022 | Enero | 2022 | Atenea | Prepago | 0 | 1 |
#separar la fecha
#data_orderdate['year']=data_orderdate['month'].astype(str)
df_sales_quarter=df.groupby([ 'year','month'])['affluence'].count().reset_index(name='afluencias').sort_values(by= 'afluencias', ascending= False)
fig=px.bar(df_sales_quarter, x='year',y = 'afluencias',color ='year')
fig.show()
import pandas as pd
import plotly.graph_objects as go
# 'tendencias'
#
tendencias = df.groupby(['service','year'])['affluence'].count().reset_index()
# Crear una figura
fig = go.Figure()
# Iterar a través de países únicos
for pais in tendencias['service'].unique():
# Filtrar datos para el país actual
data_pais = tendencias[tendencias['service'] == pais]
# Agregar una línea para cada país
fig.add_trace(go.Scatter(
x=data_pais['year'],
y=data_pais['affluence'],
mode='lines',
name=pais
))
# Personalizar el diseño del gráfico
fig.update_layout(
title='Tendencias en afluencias por Años',
xaxis_title='Año',
yaxis_title='Cantidad de afluencias',
legend_title_text='servicio',
legend=dict(
yanchor="top",
y=0.99,
xanchor="left",
x=0.01
)
)
# Agregar líneas de cuadrícula
fig.update_xaxes(showgrid=True)
fig.update_yaxes(showgrid=True)
# Mostrar el gráfico
fig.show()
import pandas as pd
import plotly.graph_objects as go
# 'tendencias'
#
tendencias = df.groupby(['service','month'])['affluence'].count().reset_index()
# Crear una figura
fig = go.Figure()
# Iterar a través de países únicos
for pais in tendencias['service'].unique():
# Filtrar datos para el país actual
data_pais = tendencias[tendencias['service'] == pais]
# Agregar una línea para cada país
fig.add_trace(go.Scatter(
x=data_pais['month'],
y=data_pais['affluence'],
mode='lines',
name=pais
))
# Personalizar el diseño del gráfico
fig.update_layout(
title='Tendencias en afluencias por Años',
xaxis_title='Mes',
yaxis_title='Cantidad de afluencias',
legend_title_text='servicio',
legend=dict(
yanchor="top",
y=0.99,
xanchor="left",
x=0.01
)
)
# Agregar líneas de cuadrícula
fig.update_xaxes(showgrid=True)
fig.update_yaxes(showgrid=True)
# Mostrar el gráfico
fig.show()
import pandas as pd
import plotly.graph_objects as go
# 'tendencias'
#
tendencias = df.groupby(['type_paiment','year'])['affluence'].count().reset_index()
# Crear una figura
fig = go.Figure()
# Iterar a través de países únicos
for pais in tendencias['type_paiment'].unique():
# Filtrar datos para el país actual
data_pais = tendencias[tendencias['type_paiment'] == pais]
# Agregar una línea para cada país
fig.add_trace(go.Scatter(
x=data_pais['year'],
y=data_pais['affluence'],
mode='lines',
name=pais
))
# Personalizar el diseño del gráfico
fig.update_layout(
title='Tendencias en afluencias por Años',
xaxis_title='Año',
yaxis_title='Cantidad de afluencias',
legend_title_text='type_paiment',
legend=dict(
yanchor="top",
y=0.99,
xanchor="left",
x=0.01
)
)
# Agregar líneas de cuadrícula
fig.update_xaxes(showgrid=True)
fig.update_yaxes(showgrid=True)
# Mostrar el gráfico
fig.show()
import pandas as pd
import plotly.graph_objects as go
# 'tendencias'
#
tendencias = df.groupby(['type_paiment','month'])['affluence'].count().reset_index()
# Crear una figura
fig = go.Figure()
# Iterar a través de países únicos
for pais in tendencias['type_paiment'].unique():
# Filtrar datos para el país actual
data_pais = tendencias[tendencias['type_paiment'] == pais]
# Agregar una línea para cada país
fig.add_trace(go.Scatter(
x=data_pais['month'],
y=data_pais['affluence'],
mode='lines',
name=pais
))
# Personalizar el diseño del gráfico
fig.update_layout(
title='Tendencias en afluencias por Años',
xaxis_title='Mes',
yaxis_title='Cantidad de afluencias',
legend_title_text='type_paiment',
legend=dict(
yanchor="top",
y=0.99,
xanchor="left",
x=0.01
)
)
# Agregar líneas de cuadrícula
fig.update_xaxes(showgrid=True)
fig.update_yaxes(showgrid=True)
# Mostrar el gráfico
fig.show()
# Elegir las dos columnas numéricas que deseas comparar
columna_x = 'service'
columna_y = 'affluence'
# Crear el gráfico de dispersión
plt.figure(figsize=(10, 6))
plt.scatter(df[columna_x], df[columna_y], alpha=0.5, color='blue')
plt.title(f'Gráfico de Dispersión entre {columna_x} y {columna_y}')
plt.xlabel(columna_x)
plt.ylabel(columna_y)
plt.grid(True)
plt.show()
# Elegir las dos columnas numéricas que deseas comparar
columna_x = 'type_paiment'
columna_y = 'affluence'
# Crear el gráfico de dispersión
plt.figure(figsize=(10, 6))
plt.scatter(df[columna_x], df[columna_y], alpha=0.5, color='blue')
plt.title(f'Gráfico de Dispersión entre {columna_x} y {columna_y}')
plt.xlabel(columna_x)
plt.ylabel(columna_y)
plt.grid(True)
plt.show()
# Excluir columnas no numéricas
numeric_df = df.select_dtypes(include=[np.number])
# Crear el mapa de calor de correlación
plt.figure(figsize=(16, 6))
heatmap = sns.heatmap(numeric_df.corr(), annot=True, cmap='BrBG')
heatmap.set_title('Mapa de calor de correlación', fontdict={'fontsize': 18}, pad=12)
plt.show()